<?php

class CertFileAccessor {
  private $_certDirPath;
  private $_networkName;
  
  public function __construct($dir, $network) {
    $this->_certDirPath = $dir;
    $this->_networkName = $network;
  }
  
  public function getPublicKey($keyName) {
    $fp = fopen($this->_certDirPath . '/' . $this->_networkName . '/' . $this->sanitizeKeyName($keyName), "r");
    
    if ($fp) {
      $pubKey = fread($fp, 8192);
      fclose($fp);
      return $pubKey;
    }
    
    return null;
  }
  
  /* modified from http://www.devdaily.com/scw/php/www.postnuke.com/PostNuke-0.750/html/includes/pnAPI.php.shtml */ 
  private function sanitizeKeyName($keyName)
  {
      static $search = array('!\.\./!si', // .. (directory traversal)
                             '!^.*://!si', // .*:// (start of URL)
                             '!^/!si',     // Forward slash (directory traversal)
                             '!^\\\\!si'); // Backslash (directory traversal)
      static $replace = array('',
                              '',
                              '_',
                              '_');

      return preg_replace($search, $replace, $keyName);
  }
}
?>
